package patrol.mobile.com.mobilepatrol.fragment;

import android.view.View;
import android.widget.Button;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.Qiaoliang;
import patrol.mobile.com.mobilepatrol.manager.QManager;
import patrol.mobile.com.mobilepatrol.persenter.QHMesPer;
import patrol.mobile.com.mobilepatrol.view.QHMesView;

/**
 * Created by apple on 17/9/29.
 */

public class InitFragment extends BaseFragment implements QHMesView {
    @BindView(R.id.bt)
    Button bt;
    private RealmAsyncTask transaction;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_init;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoading();
                QManager.clearQList2();
                Map<String, String> map = new HashMap<>();
                map.put("roadcode", "G30");
//                  map.put("spos","K2851");
//                  map.put("epos","K2923");
                QHMesPer qhMesPer = new QHMesPer(InitFragment.this, map);
                qhMesPer.getQHMes(Urls.queryQhxx);
            }
        });
    }

    @Override
    public void onQHError(String e) {

    }

    @Override
    public void onQHSuccess(final String s) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject object = new JSONObject(s);
                    if (object.getInt("state") == 200) {
                        JSONObject result = object.getJSONObject("result");
                        final JSONArray qls = result.getJSONArray("ql");
                            PatrolApp.realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.createAllFromJson(Qiaoliang.class,qls.toString());
                                }
                            });
                        hideLoading();

                    } else {
                        hideLoading();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void onStop() {
        super.onStop();
        if (transaction != null && !transaction.isCancelled()) {
            transaction.cancel();
        }
    }
}
